<?php


namespace app\controller\admin;

use app\common\model\StudentModel;
use app\model\AdminStaff;
use app\model\AdminStaffDormitoryApply;
use app\util\ReturnCode;
use think\Response;

/**
 * 申请变更宿舍列表
 */
class StaffDormitoryApply extends Base
{

    public function index(): Response
    {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $name = $this->request->get('name', '');
        $phone = $this->request->get('phone', '');
        $status = $this->request->get('status', null);

        $where = [];
        $obj = (new AdminStaffDormitoryApply());
        if ($school_id > 0) {
            array_push($where, ['AdminStaffDormitoryApply.school_id', '=', $school_id]);
        }
        if (!is_null($status)) {
            array_push($where, ['apply_status', '=', $status]);
        }
        $staffWhere = [
            ['is_delete', '=', 0]
        ];
        if ($name) {
            array_push($staffWhere, ['name', 'like', "%{$name}%"]);
        }
        if ($phone) {
            array_push($staffWhere, ['phone', '=', $phone]);
        }

        $list = $obj->where($where)->hasWhere('staff', $staffWhere)
            ->with(['staff', 'school', 'dormitory', 'student', 'oldDormitory', 'oldStudent'])
            ->order(['apply_time' => 'DESC'])
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();
        return $this->buildSuccess([
            'list' => $list['data'],
            'count' => $list['total']
        ]);
    }

    public function applyAudit(): Response {
        $id = input('post.id/d');
        $status = input('post.status/d');
        $refuse_reason = input('post.refuse_reason','','htmlspecialchars');
        $dormitoryApply = (new AdminStaffDormitoryApply())->where([
            'id' => $id
        ])->find();
        if (!$dormitoryApply) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '数据未找到');
        }
        if ($dormitoryApply->apply_status != 0) {
            return $this->buildFailed(ReturnCode::INVALID, '已审核，无法重复审核');
        }
        // 通过
        if ($status == 1) {
            $selectedArr = ['id' => $dormitoryApply->student_dormitory_id, 'permission' => [0,1,2,3]];
            StudentModel::lockAuthorization([$selectedArr], $dormitoryApply->staff_id);

            $dormitoryApply->apply_status = 1;
            $dormitoryApply->save();
        }
        // 拒绝
        else {
            $dormitoryApply->apply_status = 2;
            $dormitoryApply->refuse_reason = $refuse_reason;
            $dormitoryApply->save();
        }
        return $this->buildSuccess();
    }
}